﻿using Model.Core;
using Models;
using Newtonsoft.Json;
using SIE.SCADA.Common.Log;
using SIE.SCADA.Helper;
using SIE.SCADA.SqlSugar;
using SIE.SCADA.ZemtDemo;
using SIE.SCADA.ZemtDemo.Common;
using SIE.SCADA.ZemtDemo.MqClient;
using SIE.SCADA.ZemtDemo.MqClient.Model;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Threading;

namespace SCADA_DAQ.ZEMT.Server
{
    /// <summary>
    /// 配置上传
    /// </summary>
    public class EmployManager : MqMangerBase<EmployManager>
    {
        public string CurMatid { get; set; }
        public string linename = Env.LineName.Value;
        public event EventHandler MatcfgHandler;
        private readonly string IfaceName = "GETEMPLOYEEINFO"; //接口名称
        private readonly string EXCHANAGE = "ZEMT_MQ_EXCHANGE_GETEMPLOYEEINFO";
        private readonly string ROUTEKEY = "GETEMPLOYEEINFO_SIE";
        private AdvancedThread _thread;

        public EmployManager()
        {
            
        }

        private void TestMethod()
        {
            Request("Z002718");
        }

        //配置上传
        void Send(UserList request)
        {
            var res = mqhelper.TopicExchangePublish(request, EXCHANAGE, "", $"{IfaceName}.{linename}"
                , true, false, true, false);
            if (res.Success)
            {
                System.Diagnostics.Debug.WriteLine("数据已推送完成的！");
            }
            else
                System.Diagnostics.Debug.WriteLine("数据推送失败！\n" + res.Message);
        }

        public void Request(string userid)
        {
            if (string.IsNullOrEmpty(userid)) return;
            var _userList = new List<User>();
            var user = new User()
            {
                userId = userid
            };
            _userList.Add(user);
            UserList userList = new UserList() { userList = _userList };
            Send(userList);
        }

        public override void Start()
        {
            DataReceive();
            //TestMethod();
#if DEBUG
            RevceiveTest();
#endif
            base.Start();
        }

        void DataReceive()
        {
            //配置上传接口
            var res1 = mqhelper.TopicExchangeConsumer<EmployRoot>((data) =>
            {
                if(data.retcode.Equals("1"))
                {
                    SaveEmploy(data);
                    System.Diagnostics.Trace.WriteLine("人员信息接收成功");
                }
                return true;
            }, EXCHANAGE, $"ZEMT_MQ_SIE_{IfaceName}", $"{ROUTEKEY}.{linename}", true, false, true, false);
        }

        void SaveEmploy(EmployRoot data)
        {
            //scada_matcfg scada_Matcfg = null;
            foreach (var employDatas in data.EmployDatas)
            {
                var Employltems = employDatas.EmployItems;
                using (var ctx = pgsql.GetClient())
                {
                    foreach (var item in Employltems)
                    {
                        try
                        {
                            if (pgsql.DBClient is SmdcOrmClient ormClient)
                            {
                                var user = ormClient.SqlSugarClient.Queryable<Sys_User_UserInfo>().Where(m => m.userid_int == item.EMP_ID).First();
                                if(user != null)
                                {
                                    user.username_str = item.EMP_NAME;
                                    user.password_str = item.EMP_SERSTR;
                                    ormClient.SqlSugarClient.Updateable(user).
                                        Where(m => m.id == user.id).IgnoreColumns(it=>it == "id").ExecuteCommand();
                                }
                                else
                                {
                                    var adduser = new Sys_User_UserInfo() 
                                    { 
                                        userid_int = item.EMP_ID, 
                                        username_str = item.EMP_NAME, 
                                        password_str = item.EMP_SERSTR, 
                                    };
                                    ormClient.SqlSugarClient.Insertable(adduser).IgnoreColumns(it=>it == "id").ExecuteCommand();
                                }
                            }
                        }
                        catch (Exception ex)
                        {
                            Logger.Warn(ex.Message);
                        }
                    }
               
                }
            }
        }

        //test
        public void RevceiveTest()
        {
            TestConsumer<EmployRoot>((data) =>
            {
                SaveEmploy(data);
                return true;
            });
        }

        private Result TestConsumer<T>(Func<T, bool> funReceived)
        {
            try
            {
                try
                {
                    string line;
                    // 从文件读取并显示行，直到文件的末尾 
                    line = File.ReadAllText(@"D:\jsonStr.txt");
                    if(line.Contains("\\")) line = line.Replace("\\", @"$");
                    var msgBody = Regex.Replace(line, @"(\\[^bfrnt\\/'\""])", "\\$1");
                    var data = JsonConvert.DeserializeObject<T>(msgBody);
                    funReceived.Invoke(data);
                }
                catch (Exception ex)
                {
                    System.Diagnostics.Trace.WriteLine(ex);
                    //LoggerHelper.Logger.CreatLogger("Service").Error(ex);
                    //throw;
                }
                System.Diagnostics.Trace.WriteLine("==============TopicExchangeConsumer Start Running ！==============");
                return new Result(true);
            }
            catch (Exception ex)
            {
                return new Result(false, ex.Message);
            }
            finally
            {
                //if (channel != null) channel.Close();
                //if (conn != null) conn.Close();
            }
        }
    }

    public class User
    {
        public string userId { get; set; }
    }

    public class UserList
    {
        public List<User> userList { get; set; }
    }

}
